package com.fanshuai.metrics.jvm;

import com.codahale.metrics.*;
import com.codahale.metrics.jvm.*;

import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class JVMMetrics {
    public static void init() {
        MetricRegistry registry = new MetricRegistry();
        ConsoleReporter reporter = ConsoleReporter.forRegistry(registry).build();
        Slf4jReporter slf4jReporter = Slf4jReporter.forRegistry(registry).build();
        //reporter.start(10, TimeUnit.SECONDS);
        slf4jReporter.start(5, TimeUnit.SECONDS);

        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

        registerAll("gc", new GarbageCollectorMetricSet(), registry);
        registerAll("buffers", new BufferPoolMetricSet(mBeanServer), registry);
        registerAll("memory", new MemoryUsageGaugeSet(), registry);
        registerAll("threads", new ThreadStatesGaugeSet(), registry);
        registerAll("classLoading", new ClassLoadingGaugeSet(), registry);
        registry.register("file.descriptor.ratio", new FileDescriptorRatioGauge());
    }

    private static void registerAll(String prefix, MetricSet metricSet, MetricRegistry registry) {
        Map<String, Metric> metricMap = metricSet.getMetrics();
        for (String metricName : metricMap.keySet()) {
            Metric metric = metricMap.get(metricName);

            if (metric instanceof MetricSet) {
                registerAll(prefix + "." + metricName, (MetricSet) metric, registry);
            } else {
                registry.register(prefix + "." + metricName, metric);
            }
        }
    }
}
